// src/db.js
/**
 * making a fake database
 */
const { join } = require('path')
const fsx = require('fs-extra')
const dbDir = join(__dirname, '..', 'data')
const ext = 'json'

const getTs = () => (new Date()).getTime()

/**
 * The return result will come back with a trans_result property
 * and it's an array with src / dist inside
 * Use it to create a text file
 * @param {array} trans_result
 * @param {string} dest where to write the file
 * @return {string} written to a file
 */
function writeTxt(trans_result, dest) {
  const content = trans_result.reduce((a, b) => {
    return a + b.src + "\n" + b.dst + "\n"
  }, '')
  return fsx.writeFile(dest, content)
    .then(() => content)
}


/**
 * call it with text then just store it and create a timestamp
 * that timestamp will be the key
 * then call it again with the id and result, it will get updated
 * @param {string} text the original document
 * @param {number} [id=null] timestamp
 * @param {object} [result=null] the result object
 */
function db(text, id = null, result = null) {
  const prefix = 'job'
  if (id === null && result === null) {
    const ts = getTs()
    const json = {
      data: encodeURIComponent(text),
      id: ts
    }
    const filedir = join(dbDir, prefix + ts)
    return fsx.ensureDir(filedir)
              .then(() => fsx.writeJson(join(filedir, [ts,ext].join('.')), json)
                .then(() => ts)
              )
  }
  const filedir = join(dbDir, prefix + id)
  const file = join(filedir, [id, ext].join('.'))
  const txtfile = join(filedir, [id, 'txt'].join('.'))

  if (fsx.existsSync(file)) {
    return fsx.readJson(file)
      .then(json => {
        json.result = result
        json.complete = getTs()

        return fsx.writeJson(file, json, { spaces: 2 })
          .then(() => writeTxt(result.trans_result, txtfile))
      })
  }
  return Promise.reject(`File not found! ${file}`)
}

module.exports = { db }
